<template>
    <div class="iaa-dialog">
        <el-dialog v-model="dialogFormVisible" title="添加IAA" width="500" @close="handleCancel">
            <div style="padding: 10px;">
                <el-form :model="iaaForm" ref="iaaFormRef" :rules="rules" label-width="auto">
                    <el-form-item label="APP图标" prop="icon">
                        <el-upload class="avatar-uploader" :show-file-list="false" :http-request="uploadIcon" drag>
                            <img v-if="iaaForm.icon" :src="iaaForm.icon" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="应用名称" prop="applicationName">
                        <el-input v-model="iaaForm.applicationName" placeholder="请输入应用名称" />
                    </el-form-item>
                    <el-form-item label="简介：" prop="intro">
                        <el-input v-model="iaaForm.intro" placeholder="请输入简介" />
                    </el-form-item>
                    <el-form-item label="跟踪链接：" prop="trackingLink">
                        <el-input v-model="iaaForm.trackingLink" placeholder="请输入跟踪链接" />
                    </el-form-item>
                    <el-form-item label="渠道分组：" prop="groupId">
                        <el-select v-model="iaaForm.groupId" placeholder="请选择渠道分组" style="width: 100%">
                            <el-option v-for="item in groupOptions" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit(iaaFormRef)">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import type { UploadProps, UploadRequestOptions } from 'element-plus'
import service from '../config';
import { Plus } from '@element-plus/icons-vue'
defineComponent({ name: 'IaaAdd' })
const dialogFormVisible = ref(false)
const emit = defineEmits(['getData']);
const iaaFormRef = ref<FormInstance>()
const type = ref<string>()
const groupOptions = ref([])
interface RuleForm {
    icon: string,
    trackingLink: string,
    intro: string,
    applicationName: string,
    groupId: number
}
const iaaForm = ref<RuleForm>({
    icon: "",
    applicationName: '',
    intro: '',
    trackingLink: '',
    groupId: null
})
const rules = reactive<FormRules<RuleForm>>({
    icon: [
        { required: true, message: '请上传APP图标', trigger: 'blur' },
    ],
    applicationName: [
        { required: true, message: '请输入应用名称', trigger: 'blur' },
    ],
    intro: [{ required: true, message: '请输入简介', trigger: 'blur' }],
    trackingLink: [{ required: true, message: '请输入跟踪链接', trigger: 'blur' }],
    groupId: [{ required: true, message: '请选择渠道分组', trigger: 'change' }]
})



// 获取渠道分组数据
const getGroupOptions = () => {
    service.get('/game/getAllGroup')
        .then(response => {
            groupOptions.value = response?.data || []
        })
        .catch(error => {
            ElMessage.error(error?.message || '获取渠道分组失败')
        });
}

const uploadIcon: UploadProps['httpRequest'] = async (options: UploadRequestOptions) => {
    const formData = new FormData();
    formData.append('uploadFile', options.file as File);
    try {
        const res = await service.post('/image/uploadImage', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        iaaForm.value.icon = res.data.url
        ElMessage.success('上传成功');
        options.onSuccess && options.onSuccess(res.data as any)
    } catch (error: any) {
        ElMessage.error(error?.response?.statusText || error || '上传失败');
        options.onError && options.onError(error)
    }
}
const openModal = (_type?: string, row?: any) => {
    type.value = _type
    dialogFormVisible.value = true
    if (_type === 'edit') {
        iaaForm.value = { ...row }
    }
}
const handleCancel = () => {
    dialogFormVisible.value = false
    iaaForm.value = {
        icon: "",
        applicationName: '',
        intro: '',
        trackingLink: '',
        groupId: null
    }
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            service.post(type.value === 'add' ? 'game/add' : 'game/update', { ...iaaForm.value, })
                .then(response => {
                    ElMessage.success('提交成功！')
                    dialogFormVisible.value = false
                    iaaForm.value = {
                        icon: "",
                        applicationName: '',
                        intro: '',
                        trackingLink: '',
                        groupId: null
                    }
                    emit('getData')
                })
                .catch(error => {
                    ElMessage.error(error || '提交失败！')
                });
        } else {

        }
    })
}



onMounted(() => {
    getGroupOptions()
})

defineExpose({ openModal })
</script>

<style lang="scss">
.el-upload-dragger {
    padding: 0;
    border: none;
    border-radius: 0;
}

.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {

    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}

.iaa-dialog {
    .el-dialog {
        padding: 20px;

        .el-dialog__title {
            font-weight: 700;
        }

        .el-dialog__footer {
            padding: 0;
        }
    }

    .el-form-item {
        margin-bottom: 20px;
    }

    .el-form-item__label {
        font-size: 14px;
        font-weight: 600;
    }
}
</style>